package com.dkcd.chenshiproject.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;

import androidx.annotation.NonNull;

import com.dkcd.chenshiproject.MainActivity;
import com.dkcd.chenshiproject.activity.IndexActivity;
import com.dkcd.chenshiproject.activity.MusicPlayerActivity;
import com.dkcd.chenshiproject.adapter.MusicAdapter;
import com.dkcd.chenshiproject.entity.Song;
import com.dkcd.chenshiproject.tabHostActivity.MusicPavilionFragment;
import com.dkcd.chenshiproject.util.MusicUtils;
import com.dkcd.chenshiproject.util.SPUtils;

import java.io.IOException;
import java.util.List;

public class MusicPlayerService extends Service implements MediaPlayer.OnCompletionListener {
    private List<Song> musicData = MainActivity.musicData;
    //停止音乐
    public static final int STOP_MUSIC = 0;
    //开始音乐
    public static final int START_MUSIC = 1;
    //选择音乐
    public static final int SELECT_MUSIC = 2;
    //上一曲
    public static final int PREVIOUS_MUSIC = 3;
    //下一曲
    public static final int NEXT_MUSIC = 4;
    //修改播放状态
    public static final int PLAYER_TYPE_CHANGED = 5;
    //更改seekbar的进度
    public static final int CHANGE_SEEK_BAR_PROGRESS = 6;

    public static final int FLASH_SEEK_BAR_PROGRESS = 7;

    public static final int CHANGE_MUSIC_ID = 0x110;

    public static final int SEEK_BAR_UPDATE = 0x111;

    public static final int FLASH_SEEK_BAR = 0x011;

    public static final int PLAYING_MUSIC = 0x1011;
    private int musicPlayerType;
    public static MediaPlayer mediaPlayer = new MediaPlayer();
    private Song song;
    private int musicId;
    private Thread playerThread;
    private int currentPosition;
    public static boolean musicPlaying = true;
    //判断是谁发送来的请求
    private String maker;


    public MusicPlayerService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        Messenger messenger = new Messenger(new MusicHandler());
        return messenger.getBinder();
    }


    /**
     * @author ChenShi
     * @version：1.0
     * @date 描述: 消息处理器，
     * 选择音乐为 SELECT_MUSIC
     * 停止音乐为 STOP_MUSIC
     * 开始音乐为 START_MUSIC
     * 下一曲音乐为 NEXT_MUSIC
     * 上一曲音乐为 PREVIOUS_MUSIC
     * 修改循环规则为 PLAYER_TYPE_CHANGED
     */
    private class MusicHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            Log.e("TAG", "musicService 启动");
            super.handleMessage(msg);
            switch (msg.what) {
                //选择 音乐播放
                case SELECT_MUSIC: {
                    Log.e("TAG", "musicService 播放音乐");
                    int sendId = msg.getData().getInt("musicId");
                    maker = msg.getData().getString("maker");
                    if (sendId != musicId) {
                        MusicPlayerService.this.musicPlayerType = msg.getData().getInt("musicPlayerType");
                        currentPosition = 0;
                        musicId = sendId;
                        song = musicData.get(musicId);
                        selectMusic();
                    }
                }
                break;
                case STOP_MUSIC: {
                    Log.e("TAG", "musicService 暂停音乐");
                    musicPlaying = false;
                    mediaPlayer.pause();
                }
                break;
                case START_MUSIC: {
                    Log.e("TAG", "musicService 播放音乐");
                    musicPlaying = true;
                    mediaPlayer.start();
                }
                break;
                case NEXT_MUSIC: {
                    Log.e("TAG", "musicService 下一曲");
                    nextMusic();
                }
                break;
                case PREVIOUS_MUSIC: {
                    Log.e("TAG", "musicService 上一曲");
                    previousMusic();
                }
                break;
                case PLAYER_TYPE_CHANGED: {
                    Log.e("TAG", "musicService 修改循环规则");
                    musicPlayerType = msg.getData().getInt("musicPlayerType");
                }
                break;
                case CHANGE_SEEK_BAR_PROGRESS: {
                    Log.e("TAG", "musicService 更改seekbar的进度");
                    int progress = msg.getData().getInt("progress");
                    mediaPlayer.seekTo(progress);
                }
                break;
                case FLASH_SEEK_BAR_PROGRESS: {
                    Log.e("TAG", "musicService 刷新进度");
                    Message message = new Message();
                    message.what = FLASH_SEEK_BAR;
                    Bundle bundle = new Bundle();
                    bundle.putInt("FlashProgress", currentPosition);
                    bundle.putBoolean("mediaPlayerIsPlaying", mediaPlayer.isPlaying());
                    message.setData(bundle);
                    MusicPlayerActivity.handlers.sendMessage(message);

                }
            }
        }
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        Log.e("onCompletion", "onCompletion: 播放结束判断");
        if (musicPlayerType == 1) {
            Log.e("onCompletion", "onCompletion: 单曲循环");
            selectMusic();
            changMusicIdMessage();
        } else if (musicPlayerType == 2) {
            Log.e("onCompletion", "onCompletion: 多曲循环");
            if (musicId == musicData.size() - 1) {
                musicId = -1;
            }
            song = musicData.get(++musicId);
            selectMusic();
            changMusicIdMessage();
        } else if (musicPlayerType == 3) {
            Log.e("onCompletion", "onCompletion: 随机播放");
            int id = (int) (Math.random() * musicData.size());
            musicId = id;
            song = musicData.get(musicId);
            selectMusic();
            changMusicIdMessage();
        }
    }


    /**
     * @author ChenShi
     * @version：1.0
     * @date 描述: 选择播放音乐
     */
    private void selectMusic() {
        //替换IndexActivity 播放中的信息
        Message message1 = new Message();
        Bundle bundle1 = new Bundle();
        bundle1.putSerializable("song", musicData.get(musicId));
        message1.setData(bundle1);
        message1.what = PLAYING_MUSIC;
        IndexActivity.indexHandler.sendMessage(message1);

        //初始化播放器
        if (mediaPlayer != null) {
            mediaPlayer.reset();
        }
        String path = song.path;
        //准备播放器
        try {
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //播放器准备是否完成
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                musicPlaying = true;
                mediaPlayer.start();
            }
        });
        if (playerThread == null) {
            updateProgressBar();
        }
        //设置播放结束，判断当前循环模式
        mediaPlayer.setOnCompletionListener(this::onCompletion);
    }

    /**
     * @author ChenShi
     * @version：1.0
     * @date 描述: 下一曲
     */
    public void nextMusic() {
        if (musicId == musicData.size() - 1) {
            musicId = -1;
        }
        song = musicData.get(++musicId);
        selectMusic();
        changMusicIdMessage();
    }

    /**
     * @author ChenShi
     * @version：1.0
     * @date 描述: 上一曲
     */
    public void previousMusic() {
        if (musicId <= 0) {
            musicId = 0;
            song = musicData.get(musicId);
        } else {
            song = musicData.get(--musicId);
        }
        selectMusic();
        changMusicIdMessage();
    }

    /**
     * @author ChenShi
     * @version：1.0
     * @date 描述: 发送改变musicID的消息
     */
    private void changMusicIdMessage() {

        //更改播放页 信息
        Message message = new Message();
        message.what = CHANGE_MUSIC_ID;
        Bundle bundle = new Bundle();
        bundle.putInt("musicId", musicId);
        SPUtils.putValue(IndexActivity.indexActivity, "position",musicId);
        message.setData(bundle);
        MusicPlayerActivity.handlers.sendMessage(message);


        //更改播放页信息
        if (maker.equals("MusicPavilionFagment")) {
            Message message2 = new Message();
            message2.what = CHANGE_MUSIC_ID;
            message2.setData(bundle);
            MusicPavilionFragment.handlers.sendMessage(message2);
        }

    }


    /**
     * @author ChenShi
     * @version：1.0
     * @date 描述: 刷ProgressBar
     */

    public void updateProgressBar() {

        playerThread = new Thread() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        break;
                    }
                    Message message = new Message();
                    message.what = SEEK_BAR_UPDATE;
                    Bundle bundle = new Bundle();
                    //防止mediaPlayer reset 后 紧接着调用getCurrentPosition()方法；
                    if (mediaPlayer.isPlaying()) {
                        currentPosition = mediaPlayer.getCurrentPosition();
                    }
                    bundle.putInt("progress", currentPosition);
                    if (currentPosition / 1000 / 60 >= 10) {
                        bundle.putString("actionTime", MusicUtils.formatTime(currentPosition));
                    } else {
                        bundle.putString("actionTime", 0 + MusicUtils.formatTime(currentPosition));
                    }
                    message.setData(bundle);
                    MusicPlayerActivity.handlers.sendMessage(message);
                }
            }
        };
        playerThread.start();
    }

}